﻿using System;
using System.Collections.Generic;
using Flagwind.Services;
using Flagwind.Resources;

namespace Flagwind.Collections.Commands
{
	internal static class QueueCommandHelper
	{
		public static ICollection<IQueue> GetQueues(CommandTreeNode node, string names)
		{
			var result = new List<IQueue>();
			IQueue queue;

			if(string.IsNullOrWhiteSpace(names))
			{
				queue = FindQueue(node);

				if(queue == null)
				{
					throw new CommandException(ResourceUtility.GetString("Text.CannotObtainCommandTarget", "Queue"));
				}

				result.Add(queue);
			}
			else
			{
				foreach(var name in names.Split(',', ';'))
				{
					if(!string.IsNullOrWhiteSpace(name))
					{
						queue = FindQueue(node, name);

						if(queue == null)
						{
							throw new CommandException(ResourceUtility.GetString("Text.CannotObtainCommandTarget", $"Queue[{name}]"));
						}

						result.Add(queue);
					}
				}
			}

			return result;
		}

		private static IQueue FindQueue(CommandTreeNode node, string name = null)
		{
			if(node == null)
			{
				return null;
			}

			var queueCommand = node.Command as QueueCommand;

			if(queueCommand != null)
			{
				return name == null ? queueCommand.Queue : queueCommand.QueueProvider.GetQueue(name);
			}

			return FindQueue(node.Parent, name);
		}
	}
}